import feedparser;
from LiveSpacePageParser import LiveSpaceUpdateParser
from BlogElements import BlogEntry;
from BlogElements import BlogComment;
from BlogElements import BlogProfile;
import time;

updatePageUrl = 'http://www.blogger.com/changes10.xml';

class BloggerFeedExtractor:
    def extract(self, url):
        return url + 'feeds/posts/default';

class BloggerFeedPageParser:
    def parse(self, page):
        blogs = [];
        profile = BlogProfile();
        doc = feedparser.parse(page);
        if doc:
            if doc.feed.has_key('author_detail'):
                profile.author = doc.feed['author_detail']['name'];
            if doc.feed.has_key('title_detail'):
                profile.title = doc.feed['title_detail']['value'];
            else:
                for link in doc.feed['links']:
                    if link.has_key('title'):
                        profile.title = link['title'];
                        break;
            for entry in doc.entries:
                blog = BlogEntry();
                blog.title = entry['title'];
                blog.date = time.mktime(entry['updated_parsed']);
                if entry.has_key('content'): 
                    blog.description = entry['content'][0]['value'];
                elif entry.has_key('summary'):
                    blog.description = entry['summary'];
                blog.url = entry['link']
                for link in entry['links']:
                    href = link['href'];
                    if href.find('comment') >= 0:
                        blog.commentUrl = href;
                        break;
                blogs.append(blog);
        return profile, blogs;


class BloggerCommentPageParser:
    def parse(self, page):
        comments = [];
        doc = feedparser.parse(page);
        if doc:
            for entry in doc.entries:
                comment = BlogComment();
                comment.date = time.mktime(entry['updated_parsed']);
                if comment.has_key('content'):
                    comment.content = entry['content'][0]['value'];
                elif comment.has_key('summary'):
                    comment.content = entry['summary']; 
                comment.authorName = entry['author_detail']['name'];
                comment.authorEmail = entry['author_detail']['email'];
                comments.append(comment);

class BloggerUpdateParser:
    def __init__(self):
        self.inParser = LiveSpaceUpdateParser();
        
    def parse(self, page):
        urls = self.inParser.parse(page);
        return urls;
        
if __name__ == '__main__':
    import sys;
    if sys.argv[1] == '--feed':
        parser = BloggerFeedPageParser();
        profile, blogs = parser.parse(sys.argv[2]);
        print profile;
        for blog in blogs:
            print blog;        
        